'use strict';
const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const XLSX = require('../public/xlsx.full.min');
const db = require('./db.json');
const dbItem = require('./dbItem.json');
const table = require('./table.json');
const tableItem = require('./tableItem.json');
// const source = require('./dbSource.json');
const findEn = require('../utils/map');

function formatDate(date) {
  const year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  return year + '-' + month + '-' + day;
}

/*
* 北京时间转 unix时间戳
* 相差 70 年
* 19 个闰年
* 相差 8 个时区
* */
function beijing2Unix(beijing) {
  return ((beijing - 70 * 365 - 19) * 86400 - 8 * 3600) * 1000;
}

function transListData(startDate, endDate, source, dataItem) {
  const key = '时间';
  let list = source.filter(item => {
    const timestamp = beijing2Unix(item[key]);
    return timestamp >= (new Date(startDate + ' 00:00:00')).valueOf() && timestamp <= (new Date(endDate + ' 00:00:00')).valueOf();
  })
    .map(item => {
      let itemTime = item[key];
      itemTime = new Date(beijing2Unix(itemTime));
      return {
        ...item,
        [key]: formatDate(itemTime),
      };
    });

  list = list.map(item => {
    const newItem = Object.keys(item)
      .map(key => {
        const en = findEn(key);
        return {
          [en]: item[key],
        };
      })
      .reduce((acc, cur) => {
        cur = {
          ...acc,
          ...cur,
        };
        return cur;
      }, {});

    return {
      ...dataItem,
      ...newItem,
    };
  });

  return list;
}

function parseExcel() {
  return new Promise(resolve => {
    const buf = fs.readFileSync(path.join(__dirname, './db.xls'));
    const workbook = XLSX.read(buf, {
      type: 'buffer',
    });
    workbook.SheetNames.forEach(sheetName => {
      const XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
      if (XL_row_object.length > 0) {
        resolve(XL_row_object);
        console.log('==============================');
        console.log('excel 文件解析成功');
      } else {
        console.log('=============================');
        console.log('excel文件解析失败, 确认是否有 db.xls 文件');
        resolve([]);
      }
    });
  });
}

class HomeController extends Controller {
  async chart() {
    const source = await parseExcel();
    const { ctx } = this;
    const { st, et } = ctx.request.body;
    const list = transListData(st, et, source, dbItem);

    db.data.stats = [ ...list ];
    ctx.body = db;
  }

  async table() {
    const { ctx } = this;
    const { st, et } = ctx.request.body;
    const source = await parseExcel();
    const list = transListData(st, et, source, tableItem);

    console.log(list, '====table');
    const statistics = {
      ...tableItem,
    };
    list.forEach(item => {
      Object.keys(item)
        .forEach(key => {
          statistics[key] = parseFloat(statistics[key]) + parseFloat(item[key]);
        });
    });
    try {
      statistics.ctr = statistics.ctr.toFixed(2);
      statistics.conversion_rate = statistics.conversion_rate.toFixed(2);
      if (list.length > 0) {
        statistics.ctr = (statistics.ctr / list.length).toFixed(2);
        statistics.conversion_rate = (statistics.conversion_rate / list.length).toFixed(2);
      }
    } catch (e) {
      console.log(e);
    }
    table.data.stats = list;
    table.data.statistics = statistics;
    ctx.body = table;
  }
}

module.exports = HomeController;
